<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="设备ID" prop="deviceId">
        <el-input
          v-model="queryParams.deviceId"
          placeholder="请输入设备ID"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="设备状态" prop="deviceState">
        <el-select
          v-model="queryParams.deviceState"
          placeholder="请选择设备状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.TERMINAL_DEVICE_STATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="监测设备" prop="monitorDeviceId">
        <el-select
          v-model="queryParams.monitorDeviceId"
          placeholder="请选择监测设备"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="monitorDevice in monitorDeviceList"
            :key="monitorDevice.id"
            :label="monitorDevice.deviceName"
            :value="monitorDevice.id"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="设备分组" prop="deviceGroupId">
        <el-select
          v-model="queryParams.deviceGroupId"
          placeholder="请选择设备分组"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="deviceGroup in deviceGroupList"
            :key="deviceGroup.id"
            :label="deviceGroup.name"
            :value="deviceGroup.id"
          />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="音频流URL" prop="audioUrl">
        <el-input
          v-model="queryParams.audioUrl"
          placeholder="请输入音频流URL"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <!-- <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column label="设备ID" align="center" prop="deviceId"  :show-overflow-tooltip="true"/>
      <el-table-column label="设备名称" align="center" prop="deviceName"  :show-overflow-tooltip="true"/>
      <el-table-column label="终端型号" align="center" prop="terminal.terminalModel"  :show-overflow-tooltip="true"/>
      <el-table-column label="序列号 " align="center" prop="terminal.terminalSerialNumber"  :show-overflow-tooltip="true"/>
      <el-table-column label="设备状态" align="center" prop="deviceState" :show-overflow-tooltip="true">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TERMINAL_DEVICE_STATE" :value="scope.row.deviceState" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="监测设备" align="center" prop="monitorDeviceName" /> -->
      <el-table-column label="设备分组" align="center" prop="deviceGroupName" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="音频流URL" align="center" prop="audioUrl" /> -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="200px"
         :show-overflow-tooltip="true"
      />
      <el-table-column label="所属租户" align="center" prop="tenantName" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" width="100px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
          >
          查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TerminalDeviceForm ref="formRef" @success="getList" />

  <TerminalDeviceMgr ref="mgrRef" />

  <TerminalDeviceDetail ref="detailRef"/>

  <TerminalDeviceTenantChangeForm ref="changeTenantFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { TerminalDeviceApi, TerminalDeviceVO } from '@/api/vmiot/terminaldevice'
import TerminalDeviceForm from './TerminalDeviceForm.vue'
import TerminalDeviceDetail from  './TerminalDeviceDetail.vue'

import { DeviceGroupApi, DeviceGroupVO } from '@/api/vmiot/devicegroup'
const deviceGroupList = ref<DeviceGroupVO[]>([]) // 设备分组列表

import { MonitorDeviceApi, MonitorDeviceVO } from '@/api/vmiot/monitordevice'
import TerminalDeviceMgr from './TerminalDeviceMgr.vue'
const monitorDeviceList = ref<MonitorDeviceVO[]>([]) // 被监测设备列表

import TerminalDeviceTenantChangeForm from './TerminalDeviceTenantChangeForm.vue'

/** 终端设备 列表 */
defineOptions({ name: 'TerminalDevice' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<TerminalDeviceVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  deviceId: undefined,
  deviceName: undefined,
  deviceState: undefined,
  monitorDeviceId: undefined,
  deviceGroupId: undefined,
  audioUrl: undefined,
  remark: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TerminalDeviceApi.getAllTenantTerminalDevicePage(queryParams)
    list.value = data.list.map((item:any)=>{
      let terminalData :any ;
      try {
          terminalData = JSON.parse(item.terminalJson);
      } catch (e) {
        terminalData={};
      }
      return {
        ...item,
        terminal:terminalData
      }
    })
    console.log(list.value)
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const changeTenantFormRef = ref()
const openTenantChangeForm = (rowData: any) => {
  changeTenantFormRef.value.open(rowData)
}

const mgrRef = ref()
const openMgr = (id: number) => {
  mgrRef.value.open(id)
}


const detailRef = ref()

const openDetail = (rowData: any) => {
  detailRef.value.open(rowData)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TerminalDeviceApi.deleteTerminalDevice(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TerminalDeviceApi.exportTerminalDevice(queryParams)
    download.excel(data, '终端设备.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  deviceGroupList.value = await DeviceGroupApi.getAllDeviceGroupList()
  monitorDeviceList.value = await MonitorDeviceApi.getAllMonitorDeviceList()
})
</script>
